#  $Id: forms.py 7557b5d4d82b 2012/12/02 09:07:16 pgurumur $
#  Copyright (c) 2009 Prabhu Gurumurthy  <pgurumur@gmail.com>
#  
#  Permission to use, copy, modify, and distribute this software for any
#  purpose with or without fee is hereby granted, provided that the above
#  copyright notice and this permission notice appear in all copies.
# 
#  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
#  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
#  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
#  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
#  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
#  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

__version__ = "$Revision: 7557b5d4d82b $"
__author__ = "$Author: pgurumur $"

import string
import datetime

from django import forms
from django.contrib.auth.models import User
from django.forms import util, ValidationError

from djanet.db import choices, netdb, ssndb, query
from djanet.lib import exception, stdlib, ip
from djanet.tools.lib import tree, whois, ipv6, util
from djanet.utils import utils

class RFC4193Form(forms.Form):
   prefix = forms.BooleanField(required = False, label = 'Prefix',
         help_text = "IPv6 prefix")
   length = forms.ChoiceField(choices = choices.GetPrefixLength(),
         required = True, label = "Length", initial = "64",
         help_text = "Prefix/Address length")
   entity = forms.ChoiceField(choices = query.GetAllEntities(),
         required = False, label = "Owned By", initial = "None",
         help_text = "Owner")
   usedby = forms.ChoiceField(choices = query.GetAllEntities(),
         required = False, label = "Used By", initial = "None",
         help_text = "Used By")
   prefixtype = forms.ChoiceField(choices = choices.PREFIX_TYPES,
         required = False, label = "Prefix Type", initial = "None",
         help_text = "Prefix Type")
   description = forms.CharField(label = "Description", max_length = 128,
         widget = forms.Textarea, help_text = "Description for Prefix/Address")
   address = forms.CharField(required = False, label = "Address",
         max_length = 128, help_text = "IPv6 Prefix/Address")
   addssn = forms.BooleanField(required = False, label = "Add to SSN DB")
   insert = forms.BooleanField(required = False, label = "Insert to Netdot")

   def __init__(self, *args, **kwargs):
      super(RFC4193Form, self).__init__(*args, **kwargs)
      self._log = utils.loghandle(stdlib.my_name(self))

   def GetAddress(self, Data):
      retval = None
      length = Data["length"]
      prefix = None
      if Data["prefix"] == "false":
         prefix = False
      elif Data["prefix"] == "true":
         prefix = True

      insert = False
      if Data["insert"] == "true":
         insert = True

      addssn = False
      if Data["addssn"] == "true":
         addssn = True

      prefixtype = None
      purpose = None
      if Data["prefixtype"] != "None":
         purpose = "%s %s" %(Data["description"], string.capwords(
            Data["prefixtype"]))

      desc = None
      if purpose:
         desc = purpose
      else:
         desc = Data["description"]

      if prefix:
         flag = True
         while flag:
            ipv6cls = ipv6.rfc4193(length, prefix)
            ipv6addr = ipv6cls.GetIPv6()
            ipv6util = util.IPv6(ipv6addr)
            if ipv6util.ValidIPv6():
               flag = False
               retval = ipv6addr
               if insert:
                  netaddr = netdb.Ipblock(address = int(retval),
                        description = desc, interface = 0, parent = 0,
                        prefix = len(retval), owner = int(Data["entity"]),
                        used_by = int(Data["usedby"]), vlan = 0,
                        first_seen = datetime.datetime.now(),
                        version = retval.version)
                  netaddr.save()

               if addssn:
                  if purpose:
                     netaddr = ssndb.Ipv6Prefix(prefix = str(retval),
                           purpose = str(purpose))
                     netaddr.save(using = 'ssn')
      else:
         ipv6cls = ipv6.rfc4193(length, prefix)
         retval = ipv6cls.GetIPv6()

      return retval

